package com.ey.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.ey.config.ConstantProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author by wjx
 * @date 2021/1/26
 * @DESC:
 */
@Service
public class AliyunOOSUtil {

    public final static String OOSBaseUrl = "https://oos4web.oss-cn-hangzhou.aliyuncs.com/";
    @Autowired
    private ConstantProperties constantProperties;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 上传
     * @param file
     * @return
     */
    public  String upload(File file){
        System.out.println("=========>OSS文件上传开始："+file.getName());
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        System.out.println(endpoint+"endpoint");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                System.out.println("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            System.out.println(oe.getMessage());
            oe.printStackTrace();
//            log.error(oe.getMessage());
        }catch (ClientException ce){
            System.out.println(ce.getMessage());
            ce.printStackTrace();
//            log.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 删除
     * @param fileKey
     * @return
     */
    public  String deleteBlog(String fileKey){
        System.out.println("=========>OSS文件删除开始");
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        try {
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);

            if(!ossClient.doesBucketExist(bucketName)){
                System.out.println("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            }else {
                System.out.println("==============>开始删除Object");
                ossClient.deleteObject(bucketName,fileKey);
                System.out.println("==============>Object删除成功："+fileKey);
                return "==============>Object删除成功："+fileKey;
            }
        }catch (Exception ex){
            System.out.println("==========>删除Object失败"+ex.getMessage());
            return "删除Object失败";
        }
    }

    /**
     * 查询文件名列表
     * @param bucketName
     * @return
     */
    public List<String> getObjectList(String bucketName){
        List<String> listRe = new ArrayList<>();
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        try {
            System.out.println("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出11111目录下今天所有文件
            listObjectsRequest.setPrefix("11111/"+format.format(new Date())+"/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for(OSSObjectSummary objectSummary : list.getObjectSummaries()){
                System.out.println(objectSummary.getKey());
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        }catch (Exception ex){
            System.out.println("==========>查询列表失败"+ex.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 图片转成base64字符串
     * @param imgUrl
     * @return
     */
    public static String requestUrlToBase64(String imgUrl) {
        String result = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(imgUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 获取请求输入流
            InputStream inputStream = connection.getInputStream();
            // inputStream流数据转ByteArrayOutputStream
            int len = -1;
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

            // ByteArrayOutputStream编码成base64字符串
            result = new String(Base64.getEncoder().encode(out.toByteArray()));
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                connection.disconnect();
            }
        }
        return result;
    }

    /**
     * 上传文件至oos
     * @param file
     * @return
     */
    public String UploadToOOS(MultipartFile file) {
        System.out.println("=========>文件上传");
//        log.info("=========>文件上传");
        String uploadUrl = "";
        try {
            String filename = file.getOriginalFilename();
            if (!"".equals(filename.trim())) {
                File newFile = new File(filename);
                FileOutputStream os = new FileOutputStream(newFile);
                os.write(file.getBytes());
                os.close();
                file.transferTo(newFile);
                //上传到OSS
                uploadUrl = this.upload(newFile);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }
}